/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.pc;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class E {


    public static void main(String[] args) {
        Food2 food = new Food2();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    food.incream();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    food.decre();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

    }

}


/**
 * Synchronized锁，使用wait进行线程等待，notifyAll()进行线程的唤醒操作
 * 但是需要注意的是不能使用if语句进行判断，wait应该在while的循环体中
 *
 *
 * 除了使用Sybchronized，wait，notifyAll之外，还可以使用Lock锁进行唤醒的操作
 * 并且可以指定线程来唤醒
 *
 * Lock await signal来进行操作可以指定线程来唤醒
 */

class Food2 {
    private int num = 0;

    Lock lock = new ReentrantLock();
    //创建监视
    Condition condition = lock.newCondition();

    public  void incream() throws InterruptedException {

        //加锁操作
        lock.lock();
        try {
            while (num != 0) {
                //等待
                condition.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>" + num);
            num ++;
            //唤醒操作
            condition.signalAll();
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public  void decre() throws InterruptedException {
        lock.lock();
        try {
            while (num == 0) {
                //等待新增
                condition.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>" + num);
            num --;
            //通知其他线程我加1完毕了
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
